package ClientInitial

import (
	"encoding/base64"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"regexp"
)

func AuthorizeInterceptor() gin.HandlerFunc {
	return func(c *gin.Context) {
		authorization := c.GetHeader("Authorization") // 访问令牌
		if authorization != "" {
			if judgeBase64(authorization) {
				log.Printf("拦截器通过验证： %v", authorization)
				// 验证通过，会继续访问下一个中间件
				c.Next()
			} else {
				log.Printf("拦截器拦截请求： %v", authorization)
				// 验证不通过，不再调用后续的函数处理
				c.Abort()
				c.JSON(http.StatusUnauthorized, gin.H{"message": "访问未授权"})
			}
		} else {
			log.Printf("拦截器拦截请求： %v", authorization)
			// 验证不通过，不再调用后续的函数处理
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{"message": "访问未授权"})
		}
	}
}

func judgeBase64(str string) bool {
	pattern := "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$"
	matched, err := regexp.MatchString(pattern, str)
	if err != nil {
		return false
	}
	if !(len(str)%4 == 0 && matched) {
		return false
	}
	unCodeStr, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		return false
	}
	tranStr := base64.StdEncoding.EncodeToString(unCodeStr)
	//return str==base64.StdEncoding.EncodeToString(unCodeStr)
	if str == tranStr {
		return true
	}
	return false
}
